﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using static MyCode.Project.Infrastructure.Constant.LxmConst;

namespace MyCode.Project.Infrastructure.PayModels
{
    public static class FuiouPayHelp
    {
        private static Random random = new Random();
        public static Dictionary<string, string> buildPayObject(String sn)
        {
            Dictionary<string, string> map = new Dictionary<string, string>();
            map.Add("version", "1");
            map.Add("ins_cd", FuiouPayConst.ins_cd);
            map.Add("mchnt_cd", FuiouPayConst.mchnt_cd);
            map.Add("term_id", "");
            map.Add("random_str", Guid.NewGuid().ToString("N"));
            map.Add("sign", "");
            map.Add("order_type", "ALIPAY");
            map.Add("goods_des", "卡盟测试");
            map.Add("goods_detail", "");
            map.Add("addn_inf", "");
            map.Add("mchnt_order_no", DateTime.Now.ToString("yyyyMMddhhmmssfff") + (int)(random.NextDouble() * 100000));
            map.Add("curr_type", "");
            map.Add("order_amt", "1");
            map.Add("term_ip", FuiouPayConst.term_ip);
            map.Add("txn_begin_ts", DateTime.Now.ToString("yyyyMMddhhmmss"));
            map.Add("goods_tag", "");
            map.Add("auth_code", sn);
            map.Add("sence", "1");
            map.Add("reserved_sub_appid", "");
            map.Add("reserved_limit_pay", "");
            return map;
        }
    }

    public class FuYouPayUtils
    {
        public static Dictionary<string, string> paraFilter(Dictionary<string, string> map)
        {

            Dictionary<string, string> result = new Dictionary<string, string>();

            if (map == null || map.Count() <= 0)
            {
                return result;
            }

            foreach (string key in map.Keys)
            {
                string value = map[key];
                if (key.Equals("sign", StringComparison.CurrentCultureIgnoreCase) || (key.Length >= 8 && key.Substring(0, 8).Equals("reserved", StringComparison.CurrentCultureIgnoreCase)))
                {
                    continue;
                }
                result.Add(key, value);
            }

            return result;
        }

        public static string createLinkstring(Dictionary<string, string> map)
        {

            List<string> keys = new List<string>(map.Keys);
            keys.Sort();

            string prestr = "";

            for (int i = 0; i < keys.Count; i++)
            {
                string key = keys[i];
                string value = map[key];

                if (i == keys.Count - 1)
                {
                    //拼接时，不包括最后一个&字符
                    prestr = prestr + key + "=" + value;
                }
                else
                {
                    prestr = prestr + key + "=" + value + "&";
                }
            }

            return prestr;
        }

        public static string getSign(Dictionary<string, string> map)
        {
            Dictionary<string, string> mapNew = paraFilter(map);

            string preSignStr = createLinkstring(mapNew);
            string sign = Sign.sign(preSignStr, FuiouPayConst.privateKey);
            sign = sign.Replace("\r\n", "");
            return sign;
        }

        public static string UrlEncode(string temp, Encoding encoding)
        {
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < temp.Length; i++)
            {
                string t = temp[i].ToString();
                string k = HttpUtility.UrlEncode(t, encoding);
                if (t == k)
                {
                    stringBuilder.Append(t);
                }
                else
                {
                    stringBuilder.Append(k.ToUpper());
                }
            }
            return stringBuilder.ToString();
        }
    }

    public class Sign
    {
        public static string sign(string srcSignPacket, string privateKey)
        {
            string result = null;
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(RSAConverter.RSAPrivateKeyJava2DotNet(FuiouPayConst.privateKey));
            byte[] data = Encoding.GetEncoding(FuiouPayConst.charset).GetBytes(srcSignPacket);
            //为证书采用MD5withRSA 签名
            byte[] hashvalue = rsa.SignData(data, "MD5");

            result = Convert.ToBase64String(hashvalue);

            return result;
        }

        private static RSACryptoServiceProvider DecodeRSAPrivateKey(string privateKey)
        {
            var privateKeyBits = System.Convert.FromBase64String(privateKey);

            var RSA = new RSACryptoServiceProvider();
            var RSAparams = new RSAParameters();

            using (BinaryReader binr = new BinaryReader(new MemoryStream(privateKeyBits)))
            {
                byte bt = 0;
                ushort twobytes = 0;
                twobytes = binr.ReadUInt16();
                if (twobytes == 0x8130)
                    binr.ReadByte();
                else if (twobytes == 0x8230)
                    binr.ReadInt16();
                else
                    throw new Exception("Unexpected value read binr.ReadUInt16()");

                twobytes = binr.ReadUInt16();
                if (twobytes != 0x0102)
                    throw new Exception("Unexpected version");

                bt = binr.ReadByte();
                if (bt != 0x00)
                    throw new Exception("Unexpected value read binr.ReadByte()");

                RSAparams.Modulus = binr.ReadBytes(GetIntegerSize(binr));
                RSAparams.Exponent = binr.ReadBytes(GetIntegerSize(binr));
                RSAparams.D = binr.ReadBytes(GetIntegerSize(binr));
                RSAparams.P = binr.ReadBytes(GetIntegerSize(binr));
                RSAparams.Q = binr.ReadBytes(GetIntegerSize(binr));
                RSAparams.DP = binr.ReadBytes(GetIntegerSize(binr));
                RSAparams.DQ = binr.ReadBytes(GetIntegerSize(binr));
                RSAparams.InverseQ = binr.ReadBytes(GetIntegerSize(binr));
            }

            RSA.ImportParameters(RSAparams);
            return RSA;
        }

        private static int GetIntegerSize(BinaryReader binr)
        {
            byte bt = 0;
            byte lowbyte = 0x00;
            byte highbyte = 0x00;
            int count = 0;
            bt = binr.ReadByte();
            if (bt != 0x02)
                return 0;
            bt = binr.ReadByte();

            if (bt == 0x81)
                count = binr.ReadByte();
            else
                if (bt == 0x82)
            {
                highbyte = binr.ReadByte();
                lowbyte = binr.ReadByte();
                byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };
                count = BitConverter.ToInt32(modint, 0);
            }
            else
            {
                count = bt;
            }

            while (binr.ReadByte() == 0x00)
            {
                count -= 1;
            }
            binr.BaseStream.Seek(-1, SeekOrigin.Current);
            return count;
        }

    }
}
